package com.zyj.utils.d3.entity;

import java.util.Objects;

/**
 * 空间平面： 使用方程表示： ax + by + cz + d = 0
 */
public class Plane {
    private double a, b, c, d;

    /**
     *
     * @param A
     * @param B
     * @param C
     */
    public Plane(Point A, Point B, Point C) {
        construct(A, B, C);
    }

    /**
     * 判断点p是否在平面内
     * @param p
     * @return
     */
    public boolean pointInPlane(Point p){
        double result = a * p.x + b * p.y + c * p.z + d;
        return result == 0;
    }

    /**
     * 通过空间三点坐标，构造平面方程
     * 设方程： ax + by + cz + d = 0
     * A(x1, y1, z1), B(x2, y2, z2), C(x3, y3, z3)
     * 则：
     *      a = (y2 - y1) * (z3 - z1) - (y3 - y1) * (z2 - z1)
     *      b = (z2 - z1) * (x3 - x1) - (z3 - z1) * (x2 - x1)
     *      c = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1)
     *      d = -a * x1 - b * y1 - c * z1
     * @param A
     * @param B
     * @param C
     */
    public void construct(Point A, Point B, Point C){
        double x1 = A.x, y1 = A.y, z1 = A.z;
        double x2 = B.x, y2 = B.y, z2 = B.z;
        double x3 = C.x, y3 = C.y, z3 = C.z;

        a = (y2 - y1) * (z3 - z1) - (y3 - y1) * (z2 - z1);
        b = (z2 - z1) * (x3 - x1) - (z3 - z1) * (x2 - x1);
        c = (x2 - x1) * (y3 - y1) - (x3 - x1) * (y2 - y1);

        d = -a * x1 - b * y1 - c * z1;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        Plane plane = (Plane) o;
        return Double.compare(plane.a, a) == 0 &&
                Double.compare(plane.b, b) == 0 &&
                Double.compare(plane.c, c) == 0 &&
                Double.compare(plane.d, d) == 0;
    }

    @Override
    public int hashCode() {
        return Objects.hash(a, b, c, d);
    }
}
